
from flask_restful import Resource
from flask import request
from flask_jwt_extended import get_jwt_identity, jwt_required
from modules.dataset import DatasetModel
from modules.image import ImageModel
from common.resp import ajax_success, ajax_error, ajax_data, ajax_page
from core import db, app
from datetime import datetime
import shutil
import os

# 采集任务
class CollectionModel(db.Model):
    __tablename__ = "sys_collection"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    code = db.Column(db.String(50), nullable=False, index=True) # 采集任务代码
    name = db.Column(db.String(100), nullable=False, index=True) # 采集任务名称
    ds_id = db.Column(db.Integer, nullable=True)  # 数据集
    camera_id = db.Column(db.Integer, nullable=True)  # 摄像机
    user_id = db.Column(db.Integer, nullable=True)  # 标注用户
    status = db.Column(db.String(10), default="1")  #状态 禁用 启用 运行中
    start_time = db.Column(db.DateTime, nullable=True, default=datetime.now)
    end_time = db.Column(db.DateTime, nullable=True, default=datetime.now)
    create_time = db.Column(db.DateTime, nullable=True, default=datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, default=datetime.now, onupdate=datetime.now)

    def to_json(self):
        return {
            'id': self.id,
            'code': self.code,
            'name': self.name,
            'ds_id': self.ds_id,
            'camera_id': self.camera_id,
            'user_id': self.user_id,
            'status': self.status,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S') if self.start_time else None,
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
        }

class CollectionResource(Resource):
    def get(self):
        query = request.args;
        filters = []
        if query.get('name'):
            filters.append(CollectionModel.name.like('%' + query['name'] + '%'))
        if query.get('code'):
            filters.append(CollectionModel.code.like('%' + query['code'] + '%'))
        if query.get('status'):
            filters.append(CollectionModel.status == query['status'])
        if query.get('ds_id'):
            filters.append(CollectionModel.ds_id == int(query['ds_id']))
        if query.get('user_id'):
            filters.append(CollectionModel.user_id == int(query['user_id']))
        if query.get('camera_id'):
            filters.append(CollectionModel.camera_id == int(query['camera_id']))

        paginate = CollectionModel.query.filter(
            *filters).paginate(
            page=int(query.get('page', 1)), per_page=int(query.get('limit', 10)), error_out=False)

        return ajax_page([item.to_json() for item in paginate.items], paginate.total)

    def post(self):
        data = request.get_json()
        model = CollectionModel(
            code = data.get('code'),
            name = data.get('name'),
            ds_id = data.get('ds_id'),
            camera_id = data.get('camera_id'),
            user_id = data.get('user_id'),
            status = data.get('status', '1')
        )

        db.session.add(model)
        db.session.commit()
        return ajax_success('采集任务创建成功')

    def put(self):
        data = request.get_json()
        if not data.get('id'):
            return ajax_error('参数错误')

        model = CollectionModel.query.get_or_404(data.get('id'))
        if not model:
            return ajax_error('采集任务不存在')

        if data.get('name'):
            model.name = data.get('name', model.name)
        if data.get('status'):
            model.status = data.get('status', model.status)
        if data.get('ds_id'):
            model.ds_id = data.get('ds_id', model.ds_id)
        if data.get('camera_id'):
            model.camera_id = data.get('camera_id', model.camera_id)
        if data.get('user_id'):
            model.user_id = data.get('user_id', model.user_id)
        if data.get('code'):
            model.code = data.get('code', model.code)    

        db.session.add(model)
        db.session.commit()
        return ajax_success('采集任务更新成功')

class CollectionDetail(Resource):
    def get(self, id):
        if id:
            model = CollectionModel.query.get_or_404(id)
            return ajax_data(model.to_json())
        else:
            return ajax_error('参数错误')

    def delete(self, id):
        collection = CollectionModel.query.get_or_404(id)
        dataset = DatasetModel.query.get_or_404(collection.ds_id)
        images = ImageModel.query.filter(ImageModel.ds_id == collection.ds_id, ImageModel.camera_id == collection.camera_id).all();
        dsPath = os.path.join(app.config['DATASET_PATH'], dataset.path)
        for image in images:
            db.session.delete(image)
            imgPath = os.path.join(dsPath, image.name)
            if os.path.exists(imgPath):
                os.remove(imgPath)
       
        db.session.delete(collection)
        db.session.commit()
        return ajax_success('采集任务删除成功')
